# -*- coding: utf-8 -*-
from future.utils import raise_with_traceback

from common import orm
from common.account.db.account import add_campaign_award_in_transaction
from common.campaign.model.daily_bet_return import DailyBetReturn, DAILY_BET_AWARD, DAILY_BET_GAME_TYPE
from common.notification.handler import generate_user_notification, notify_award_success
from common.utils.decorator import sql_wrapper
from common.utils.exceptions import ConfigError


@sql_wrapper
def get_daily_bet(user_id, game_type, date_str):
    daily_bet = DailyBetReturn.query. \
        filter(DailyBetReturn.user_id == user_id). \
        filter(DailyBetReturn.game_type == game_type). \
        filter(DailyBetReturn.date == date_str). \
        first()
    return daily_bet


@sql_wrapper
def set_daily_bet(user_id, game_type, amount, date_str):
    daily_bet = get_daily_bet(user_id, game_type, date_str)
    if not daily_bet:
        daily_bet = DailyBetReturn()
        daily_bet.user_id = user_id
        daily_bet.date = date_str
        daily_bet.game_type = game_type
        daily_bet.save()
    daily_bet.amount = amount
    daily_bet.save()
    return daily_bet


def award_daily_bet(user_id, game_type, amount, date_str):
    award_settings = DAILY_BET_AWARD.get(game_type)
    if not award_settings:
        raise ConfigError('game_type not found in daily_bet_award settings')

    award_amount = 0
    for k in award_settings:
        if amount >= k:
            award_amount = max(award_amount, award_settings[k])

    if award_amount <= 0:
        return
    try:
        extend = {
            'title': u'流水闯关活动奖励',
            'award_amount': award_amount
        }
        daily_bet = DailyBetReturn.query.with_for_update(). \
            filter(DailyBetReturn.user_id == user_id). \
            filter(DailyBetReturn.game_type == game_type). \
            filter(DailyBetReturn.date == date_str). \
            filter(DailyBetReturn.transaction_id.is_(None)). \
            filter(DailyBetReturn.is_awarded == 0).first()

        if daily_bet:
            transaction_id = add_campaign_award_in_transaction(user_id, award_amount, extend)
            daily_bet.is_awarded = 1
            daily_bet.amount = amount
            daily_bet.transaction_id = transaction_id
            daily_bet.save(auto_commit=False)
            orm.session.commit()
            if game_type == DAILY_BET_GAME_TYPE.LOTTERY:
                notify_award_success(user_id, u'流水闯关', u'购彩', award_amount)
            elif game_type == DAILY_BET_GAME_TYPE.CASINO:
                notify_award_success(user_id, u'流水闯关', u'电玩城', award_amount)
        else:
            orm.session.commit()
    except Exception as e:
        orm.session.rollback()
        orm.session.close()
        raise_with_traceback(e)
